<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import videojs from "video.js";
import "video.js/dist/video-js.css";
import { useDeviceStore } from "@/store/modules/device"; // 引入设备状态仓库
import SvgIcon from "@/components/SvgIcon/index.vue";

// 获取设备状态
const deviceStore = useDeviceStore();

// 判断是否为移动设备
const isMobileDevice = computed(() => {
  return deviceStore.isMobile;
});

const props = defineProps({
  src: {
    type: String,
    required: true,
  },
  poster: {
    type: String,
    default: "",
  },
  autoplay: {
    type: Boolean,
    default: true,
  },
  muted: {
    type: Boolean,
    default: true,
  },
  loop: {
    type: Boolean,
    default: true,
  },
  controls: {
    type: Boolean,
    default: false,
  },
  isActive: {
    type: Boolean,
    default: false,
  },
  fit: {
    type: String,
    default: "contain", // 'contain' 显示全部内容，'cover' 填充满容器
    validator: (value) => ["contain", "cover", "fill"].includes(value),
  },
  showControls: {
    type: Boolean,
    default: true,
  },
  // 添加新的prop，用于控制是否记录历史
  recordHistory: {
    type: Boolean,
    default: false,
  },
  // 添加视频ID，用于记录历史
  videoId: {
    type: [String, Number],
    default: null,
  },
  // 添加进度阈值，当播放进度超过此值时记录历史
  historyThreshold: {
    type: Number,
    default: 0.3, // 默认30%
  },
  // 添加初始音量设置
  initialVolume: {
    type: Number,
    default: 0.2, // 默认最大音量
    validator: (value) => value >= 0 && value <= 1, // 确保音量在0-1之间
  },
});

// 添加新的emit事件
const emit = defineEmits([
  "play",
  "pause",
  "ended",
  "update:fit",
  "recordHistory",
]);

const videoRef = ref(null);
const containerRef = ref(null);
const controlsVisible = ref(false);
let player = null;
let hideControlsTimeout = null;
const isPaused = ref(true);
const currentTime = ref(0);
const duration = ref(0);
const volume = ref(1);
const isMuted = ref(props.muted);
const isFullscreen = ref(false);

// 初始化视频播放器
const initializePlayer = () => {
  if (videoRef.value) {
    player = videojs(videoRef.value, {
      autoplay: props.autoplay,
      muted: props.muted,
      loop: props.loop,
      controls: false, // 设置为false，我们自己控制UI
      fluid: false,
      playsinline: true,
      preload: "auto",
      poster: props.poster,
      sources: [
        {
          src: props.src,
          type: "video/mp4",
        },
      ],
    });

    // 设置初始音量
    player.volume(props.initialVolume);

    player.on("play", () => {
      isPaused.value = false;
      emit("play");
    });

    player.on("pause", () => {
      isPaused.value = true;
      emit("pause");
    });

    player.on("ended", () => {
      emit("ended");
    });

    player.on("timeupdate", () => {
      currentTime.value = player.currentTime();

      // 计算当前播放进度百分比
      const currentPercentage = currentTime.value / duration.value;

      // 当视频播放超过阈值且未记录过历史且需要记录历史时
      if (
        props.recordHistory &&
        props.videoId &&
        currentPercentage >= props.historyThreshold &&
        !historyRecorded.value &&
        duration.value > 0
      ) {
        historyRecorded.value = true;
        emit("recordHistory", props.videoId);
      }
    });

    player.on("loadedmetadata", () => {
      duration.value = player.duration();
    });

    player.on("volumechange", () => {
      volume.value = player.volume();
      isMuted.value = player.muted();
    });

    player.on("fullscreenchange", () => {
      isFullscreen.value = player.isFullscreen();
    });

    // 应用自定义样式到视频元素
    applyVideoFitStyle();
  }
};

// 应用视频适配样式
const applyVideoFitStyle = () => {
  if (!player) return;

  const videoElement = player.el().querySelector("video");
  if (videoElement) {
    videoElement.style.objectFit = props.fit;
    videoElement.style.width = "100%";
    videoElement.style.height = "100%";
  }
};

// 切换视频适配模式
const toggleFitMode = () => {
  const modes = ["contain", "cover", "fill"];
  const currentIndex = modes.indexOf(props.fit);
  const nextIndex = (currentIndex + 1) % modes.length;
  emit("update:fit", modes[nextIndex]);
};

// 修改显示控制器的方法
const showControlsHandler = () => {
  // 由于控制器现在在外部区域，我们可以选择不自动隐藏它
  // 或者设置较长的自动隐藏时间
  controlsVisible.value = true;

  // 如果仍然需要自动隐藏，可以保留以下代码
  // clearTimeout(hideControlsTimeout);
  // hideControlsTimeout = setTimeout(() => {
  //   if (!isControlsHovered.value) {
  //     controlsVisible.value = false;
  //   }
  // }, 5000); // 延长显示时间
};

// 添加控制器悬停状态
const isControlsHovered = ref(false);

// 鼠标进入控制器区域
// const handleControlsMouseEnter = () => {
//   isControlsHovered.value = true;
//   clearTimeout(hideControlsTimeout);
// };

// // 鼠标离开控制器区域
// const handleControlsMouseLeave = () => {
//   isControlsHovered.value = false;
//   // 离开控制器区域后，如果1.5秒内没有其他交互，则隐藏控制器
//   hideControlsTimeout = setTimeout(() => {
//     controlsVisible.value = false;
//   }, 1500);
// };

// 添加以下部分来取消视频点击时的控制器显示/隐藏切换
// 仅当视频暂停时点击才会切换播放状态
const handleVideoClick = (event) => {
  // 阻止事件冒泡，避免重复触发
  event.stopPropagation();

  // 如果用户点击了控制器区域，不切换播放状态
  // if (event.target.closest(".video-controls")) {
  //   return;
  // }

  togglePlay();
};

// 切换播放/暂停
const togglePlay = () => {
  showControlsHandler();
  if (player.paused()) {
    player.play();
  } else {
    player.pause();
  }
};

// 切换静音
const toggleMute = () => {
  showControlsHandler();
  player.muted(!player.muted());
};

// 修改音量
const changeVolume = (value) => {
  showControlsHandler();
  player.volume(value);
  // 如果音量大于0，取消静音
  if (value > 0 && player.muted()) {
    player.muted(false);
  }
  // 如果音量为0，静音
  if (value === 0 && !player.muted()) {
    player.muted(true);
  }
};

// 切换全屏
const toggleFullscreen = () => {
  showControlsHandler();
  if (player.isFullscreen()) {
    player.exitFullscreen();
  } else {
    player.requestFullscreen();
  }
};

// 格式化时间为 mm:ss 格式
const formatTime = (seconds) => {
  if (isNaN(seconds) || seconds < 0) return "00:00";

  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

// 进度条点击事件
const onProgressClick = (event) => {
  const progressBar = event.currentTarget;
  const rect = progressBar.getBoundingClientRect();
  const percentage = (event.clientX - rect.left) / rect.width;
  const seekTime = duration.value * percentage;

  player.currentTime(seekTime);
  showControlsHandler();
};

// 计算播放进度百分比
const progressPercentage = computed(() => {
  if (duration.value === 0) return 0;
  return (currentTime.value / duration.value) * 100;
});

const historyRecorded = ref(false);

// 当组件挂载时初始化播放器
onMounted(() => {
  initializePlayer();

  // 初始状态设置
  if (player) {
    isPaused.value = player.paused();
    isMuted.value = player.muted();
    volume.value = player.volume();
  }

  // 鼠标移动时显示控件
  const container = containerRef.value;
  if (container) {
    container.addEventListener("mousemove", showControlsHandler);
    container.addEventListener("click", showControlsHandler);
  }

  // 确保设备检测已运行
  deviceStore.checkDevice();
});

// 当组件卸载时销毁播放器
onUnmounted(() => {
  if (player) {
    player.dispose();
  }
  clearTimeout(hideControlsTimeout);

  const container = containerRef.value;
  if (container) {
    container.removeEventListener("mousemove", showControlsHandler);
    container.removeEventListener("click", showControlsHandler);
  }
});

// 监听 isActive 属性变化，控制视频播放和暂停
watch(
  () => props.isActive,
  (newVal) => {
    if (!player) return;

    if (newVal) {
      player.play();
      isPaused.value = false;
    } else {
      player.pause();
      isPaused.value = true;
      // 当视频不再活跃时重置历史记录状态
      historyRecorded.value = false;
    }
  },
  { immediate: true }
);

// 监听 fit 属性变化
watch(
  () => props.fit,
  () => {
    applyVideoFitStyle();
  }
);

// 监听src变化时重置历史记录标志
watch(
  () => props.src,
  () => {
    historyRecorded.value = false;
  }
);

// 提供给父组件的方法
defineExpose({
  play() {
    player?.play();
  },
  pause() {
    player?.pause();
  },
  toggleFitMode,
});
</script>

<template>
  <div class="video-player-wrapper">
    <!-- 视频容器 -->
    <div class="video-player-container" ref="containerRef">
      <video
        ref="videoRef"
        class="video-js vjs-big-play-centered"
        data-setup="{}"
      ></video>

      <!-- 在 VideoPlayer.vue 的视频覆盖层 -->
      <div class="video-overlay" @click="handleVideoClick">
        <div class="pause-indicator" v-if="isPaused && player">
          <SvgIcon icon-class="play" :size="isMobileDevice ? 60 : 80" />
        </div>
        <slot></slot>
        <!-- 保持 VideoInfo 在视频上显示 -->
      </div>
    </div>

    <!-- 控制区域，移至视频下方 -->
    <div
      class="video-controls-external"
      v-if="showControls"
      :class="{ 'mobile-controls': isMobileDevice }"
    >
      <!-- 进度条部分 -->
      <div class="progress-container" @click="onProgressClick">
        <div class="progress-bar">
          <div
            class="progress-fill"
            :style="{ width: `${progressPercentage}%` }"
          ></div>
          <!-- 进度条拖动点 -->
          <div
            class="progress-handle"
            :style="{ left: `${progressPercentage}%` }"
          ></div>
        </div>
      </div>

      <!-- 控制按钮和信息部分 -->
      <div class="controls-main" v-if="!isMobileDevice">
        <!-- 左侧控制按钮组 -->
        <div class="controls-left">
          <!-- 播放/暂停按钮 -->
          <button class="control-btn" @click.stop="togglePlay">
            <SvgIcon :icon-class="isPaused ? 'play' : 'pause'" :size="16" />
          </button>

          <!-- 音量控制 -->
          <div class="volume-control">
            <button class="control-btn" @click.stop="toggleMute">
              <SvgIcon
                :icon-class="
                  isMuted
                    ? 'volume-off'
                    : volume > 0.5
                    ? 'volume-up'
                    : 'volume-down'
                "
                :size="16"
              />
            </button>
            <input
              type="range"
              min="0"
              max="1"
              step="0.1"
              :value="isMuted ? 0 : volume"
              @input="changeVolume($event.target.value)"
              class="volume-slider"
              @click.stop
            />
          </div>

          <!-- 时间信息 -->
          <div class="time-info">
            {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
          </div>
        </div>

        <!-- 右侧控制按钮组 -->
        <div class="controls-right">
          <!-- 全屏按钮 -->
          <button class="control-btn" @click.stop="toggleFullscreen">
            <SvgIcon
              :icon-class="isFullscreen ? 'fullscreen-exit' : 'fullscreen'"
              :size="16"
            />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.video-player-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  position: relative;
}

.video-player-container {
  position: relative;
  width: 100%;
  flex-grow: 1; // 占据除控制区域外的所有高度
  overflow: hidden;
  background-color: #000;

  .video-js {
    width: 100%;
    height: 100%;
  }

  :deep(video) {
    position: absolute;
    width: 100%;
    height: 100%;
  }

  .video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    z-index: 1;
  }

  .pause-indicator {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80px;
    height: 80px;
    background-color: rgba(155, 153, 153, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3;
  }
}

// 外部控制区域样式
.video-controls-external {
  width: 100%;
  background-color: #111; // 深色背景
  border-top: 1px solid #222; // 上边框分隔
  display: flex;
  flex-direction: column;
  z-index: 2;
  padding: 0 16px; // 默认桌面端的内边距
  &.mobile-controls {
    padding: 0; // 移除内边距
    background-color: rgba(17, 17, 17, 0.7); // 较透明的背景
    border-top: none; // 移除边框
    position: absolute; // 绝对定位
    bottom: 0; // 放置在视频底部
    left: 0;

    .progress-container {
      height: 20px; // 增大触摸区域
      padding: 8px 16px; // 添加内边距使触摸更容易

      .progress-bar {
        height: 4px;

        &:hover {
          height: 4px; // 移动端不需要悬停效果
          margin: 0;
        }

        // 增大拖动点大小，适合触摸操作
        .progress-handle {
          width: 16px;
          height: 16px;
        }
      }
    }
  }

  .progress-container {
    width: 100%;
    height: 16px;
    padding: 4px 0;
    cursor: pointer;

    .progress-bar {
      height: 4px;
      width: 100%;
      background-color: rgba(255, 255, 255, 0.3);
      border-radius: 2px;
      position: relative;
      overflow: visible; // 允许进度条拖动点溢出容器

      .progress-fill {
        height: 100%;
        background-color: #3490dc;
        position: absolute;
        left: 0;
        top: 0;
        border-radius: 2px;
      }

      // 拖动点样式
      .progress-handle {
        position: absolute;
        top: 50%;
        width: 12px;
        height: 12px;
        background-color: #fff;
        border-radius: 50%;
        transform: translate(-50%, -50%);
        box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
        z-index: 1;

        &:hover {
          transform: translate(-50%, -50%) scale(1.2);
        }
      }

      &:hover {
        height: 6px; // 鼠标悬停时增加进度条高度
        margin-top: -1px;
        margin-bottom: -1px;
      }
    }
  }

  .controls-main {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .controls-left {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .controls-right {
      display: flex;
      align-items: center;
    }

    .time-info {
      color: white;
      font-size: 12px;
      min-width: 80px;
    }
  }

  .control-btn {
    background: none;
    border: none;
    color: white;
    cursor: pointer;
    padding: 6px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background-color: rgba(255, 255, 255, 0.2);
    }
  }

  .volume-control {
    display: flex;
    align-items: center;
    gap: 8px;

    .volume-slider {
      width: 70px;
      height: 4px;
      -webkit-appearance: none;
      appearance: none;
      background: rgba(255, 255, 255, 0.3);
      border-radius: 2px;
      outline: none;

      &::-webkit-slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background: white;
        cursor: pointer;
      }

      &::-moz-range-thumb {
        width: 12px;
        height: 12px;
        border: none;
        border-radius: 50%;
        background: white;
        cursor: pointer;
      }
    }
  }
}

:deep(.vjs-big-play-button) {
  display: none !important;
}

:deep(.vjs-control-bar) {
  display: none !important;
}

:deep(.vjs-tech) {
  object-position: center;
}
</style>
